<template>
  <main-box>
    <PlusSearch
      v-model="queryform"
      :columns="formConfig"
      :show-number="2"
      label-width="80"
      label-position="right"
      class="mb-xs"
      @search="initData(true)"
      @reset="handleRest"
    >
      <template #plus-field-warehouseId>
        <k-select-http
          v-model="queryform.warehouseId"
          paramsKey="searchValue"
          :immediately="true"
          :httpfn="getWarehouseList"
          :keyprops="{ label: 'name', value: 'warehouseId' }"
        />
      </template>
    </PlusSearch>
    <div class="mb-2">
      <btnExport
        :exportApi="exportApi"
        :queryform="queryform"
        download-name="工具定检统计"
      />
    </div>
    <PureTable
      ref="tableRef"
      border
      adaptive
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :pagination="pagination"
      @page-size-change="initData()"
      @page-current-change="initData(false)"
    />
  </main-box>
</template>

<script setup lang="tsx">
import { ref } from "vue";
import { useTableConfig } from "@/utils/tableConfig";
import { type PlusColumn, PlusSearch } from "plus-pro-components";
import btnExport from "@/components/btnExport/index.vue";

import { listApi, exportApi } from "@/api/statistics/inspect";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { useRouter } from "vue-router";

import kSelectHttp from "@/components/k-select-http/index.vue";
import { allListApi as getWarehouseList } from "@/api/warehouse";

import { diffDate } from "@/utils";
import dayjs from "dayjs";

/* 查询表单 */
const formConfig: PlusColumn[] = [
  {
    label: "定检时间",
    prop: "time",
    valueType: "date-picker",
    fieldProps: {
      type: "daterange",
      valueFormat: "YYYY-MM-DD"
    }
  },
  {
    label: "工具室",
    prop: "warehouseId"
  },
  {
    label: "查询",
    prop: "searchValue",
    fieldProps: { placeholder: "物品名称/编号/型号" }
  }
];

const warehouseId = (window as any).datasource;

const queryform = ref({
  time: [],
  warehouseId: warehouseId > 0 ? warehouseId : "",
  searchValue: ""
} as any);

const getQueryParam = () => {
  const params = {
    ...queryform.value
  } as any;
  if (params.time && params.time.length) {
    params.params = {
      startTime: params.time[0],
      endTime: params.time[1]
    };
  }
  delete params.time;
  return params;
};

const handleRest = () => {
  initData(true);
};

/* 表格数据 */
const { pagination } = useTableConfig();
const tableData = ref([]);
const loading = ref(false);
const columns = [
  {
    label: "物件图片",
    prop: "picUrl",
    cellRenderer: ({ row }) => {
      const { picUrl } = row;
      let list = [];
      if (picUrl) {
        list = picUrl.split(",");
      }
      return list.map((item, index) => {
        return (
          <el-image
            src={item}
            width={50}
            initial-index={index}
            preview-src-list={list}
            preview-teleported={true}
          />
        );
      });
    }
  },
  { label: "物件编号", prop: "code" },
  { label: "物件名称", prop: "name" },
  { label: "分类", prop: "toolCategoryName" },
  { label: "物件型号", prop: "modelName" },
  { label: "标签编码", prop: "labelCode" },
  { label: "工具室", prop: "warehouseName" },
  { label: "存放位置", prop: "storageLocation" },

  { label: "定检时间", prop: "inspectTime", sortable: true },
  {
    label: "剩余时间",
    prop: "inspectTime",

    cellRenderer: ({ row }) => {
      if (!row.inspectTime) {
        return "";
      }
      const { inspectTime } = row;
      const endTime = dayjs(dayjs(inspectTime).format("YYYY-MM-DD"));
      const startTime = dayjs(dayjs().format("YYYY-MM-DD"));
      const time = dayjs(endTime).diff(startTime, "day");
      const col = time < 0 ? "danger" : "default";
      return (
        <el-link type={col} underline={false}>
          {time}天
        </el-link>
      );
    },
    sortable: true
  },
  { label: "累计定检", prop: "totalInspectCount", sortable: true },

  {
    label: "操作",
    prop: "action",
    cellRenderer: ({ row }) => (
      <el-link underline={false} type="primary" onClick={() => goDetail(row)}>
        查看
      </el-link>
    )
  }
];

const initData = async (needInit = true) => {
  loading.value = true;
  if (needInit) {
    pagination.currentPage = 1;
  }
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    ...getQueryParam()
  } as any;

  await listApi(params)
    .then(res => {
      tableData.value = res.rows;
      pagination.total = Number(res.total);
    })
    .catch(() => (loading.value = false));
  loading.value = false;
};

initData();

/* 操作 */
const router = useRouter();
const goDetail = row => {
  const query = {
    path: "/tools/detail",
    query: { id: String(row.toolId) },
    name: "ToolDetailIndex"
  };
  useMultiTagsStoreHook().handleTags("push", {
    ...query,
    meta: {
      title: "工具详情",
      dynamicLevel: 1
    }
  });
  router.push(query);
};
</script>
